import { ArgumentsHost, HttpStatus } from '@nestjs/common';
import {
  ResponseMsgKey,
  ApiResponse,
} from '../constants/api-response.constant';
import { I18nContext } from 'nestjs-i18n';

export class ResponseUtil {
  public static readonly index: string = 'index';

  public static ok<T = any>(data: T = null): ApiResponse<T> {
    return {
      data,
      code: HttpStatus.OK,
      message: ResponseUtil.translate(ResponseMsgKey.SUCCESS),
    };
  }

  public static fail(
    code: number = HttpStatus.BAD_REQUEST,
    message: string = ResponseMsgKey.FAIL,
  ): ApiResponse<any> {
    return {
      data: null,
      code,
      message,
    };
  }

  public static translate(key: string | string[], context?: ArgumentsHost) {
    const index = ResponseUtil.index;
    try {
      const i18n = I18nContext.current(context);
      const getTranslation = (key: string) => {
        const msg = i18n.t(`${index}.${key}`, {
          lang: i18n.lang,
        });
        return msg === `${index}.${key}` ? key : msg;
      };
      return Array.isArray(key)
        ? key.map((r) => getTranslation(r)).join(',')
        : getTranslation(key);
    } catch {
      return Array.isArray(key) ? key.join(',') : key;
    }
  }
}
